package net.sk.china.front.service.impl.city;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import net.sk.china.common.constants.Constants;
import net.sk.china.common.model.city.City;
import net.sk.china.common.utils.RedisUtil;
import net.sk.china.front.dao.city.CityDao;
import net.sk.china.front.service.city.CityService;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * CityServiceImpl 接口实现
 * +----------------------------------------------------------------------
 * | Talk To [ 聊来改善地区金融服务环境，助力企业发展 ]
 * +----------------------------------------------------------------------
 * | Copyright (c) 2018-2024 聊来All rights reserved.
 * +----------------------------------------------------------------------
 * | Licensed ( <a href="http://www.apache.org/licenses/LICENSE-2.0">apache</a> )
 * +----------------------------------------------------------------------
 * | @Author: 聊来 <18970881148@qq.com>
 * +----------------------------------------------------------------------
 * | DateTime: 2024/6/13 22:11
 * +----------------------------------------------------------------------
 */
@Service
public class CityServiceImpl extends ServiceImpl<CityDao, City> implements CityService {

    @Resource
    private CityDao dao;

    private final RedisUtil redisUtil;

    public CityServiceImpl(RedisUtil redisUtil) {
        this.redisUtil = redisUtil;
    }

    /**
     * 通过行政编码编码获取数据
     * @return {@code City}
     */
    @Override
    public City asyncRedisCity() {
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        String areaCode = request.getHeader(net.sk.china.front.constants.Constants.CITY_AREA_CODE);
        if (ObjectUtil.isNull(areaCode)) { return null; }
        City city = (City) redisUtil.hmGet(Constants.CITY_ACCOUNT, areaCode);
        if (ObjectUtil.isNull(city)) {
            LambdaQueryWrapper<City> query = new LambdaQueryWrapper<>();
            query.eq(City::getParentId, net.sk.china.front.constants.Constants.NUM_ZERO).eq(City::getAreaCode, areaCode).eq(City::getRoles, "1");
            query.last("limit 1");

            city = dao.selectOne(query);
            if (ObjectUtil.isNotNull(city)) { redisUtil.hmSet(Constants.CITY_ACCOUNT, areaCode, city); }

        }

        return city;
    }
}
